<template>
    <div ref="containerRef" :style="{
        width: '100%',
        height: '100%',
        overflow: 'hidden',
        position: 'relative'
    }">

        <div class="button" v-if="!isStartLoading" @click="handleButtonClick">
            3D >
        </div>
        <!-- 全屏按钮 -->
        <button class="fs-btn" v-if="isModelLoaded" @click="toggleFullscreen" aria-label="toggle fullscreen">
            {{ isFullscreen ? '×' : '⛶' }}
        </button>
        <!-- 预览图：当模型未加载时显示 -->
        <img v-if="!isStartLoading" :src="previewImage" :style="{
            width: '100%',
            height: '100%',
            objectFit: 'cover',
            display: 'block'
        }">
        <div class="my-progress" v-if="isLoading">
            <!-- 进度条的外层轨道 -->
            <div class="my-progress-bar">
                <!-- 进度条的内层滑块，宽度由 style 动态控制 -->
                <div class="my-progress-bar__inner" :style="{ width: percentage + '%' }">
                </div>
            </div>
            <span class="my-progress-bar__text">{{ percentage }}%</span>
        </div>
        <!-- 为 Three.js 创建一个专门的容器，并给它一个 ref -->
        <div ref="threeContainerRef" style="width: 100%; height: 100%;"></div>
    </div>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount } from 'vue';
import { ThreeManager } from '../utils/threeManager';

const props = defineProps({
    modelUrl: { type: String, required: true },//加载的 3D 模型文件的 URL，为.glb格式
    background: { type: String, default: '0x808080' },//背景色
    cameraZ: { type: Number, default: 2.2 },//相机离模型的距离
    autoRotate: { type: Boolean, default: true },//是否自动旋转
    rotationSpeed: { type: Number, default: 0.007 },//自动旋转速率
    previewImage: ''// 预览图片
});

let threeManager = null; // 存放 ThreeManager 的实例

const containerRef = ref(null);
const threeContainerRef = ref(null);
const isStartLoading = ref(false);
const isLoading = ref(false);
const percentage = ref(0);
const isModelLoaded = ref(false);
const isFullscreen = ref(false);

const handleButtonClick = async () => {
    isStartLoading.value = !isStartLoading.value;
    isLoading.value = true;
    percentage.value = 1; // 避免初始占满，给一个最小起始宽度
    await nextTick();
    threeManager = new ThreeManager(threeContainerRef.value, props);
    threeManager.init();
    threeManager.loadModel(
        props.modelUrl,
        () => { // onComplete
            isLoading.value = false;
            isModelLoaded.value = true;
        },
        (progress) => { // onProgress
            percentage.value = progress;
        },
        (err) => {
            console.log('模型加载失败');
        }
    );
};

// 全屏功能
const toggleFullscreen = () => {
    const el = containerRef.value;
    if (!el) return;
    if (!document.fullscreenElement) {
        el.requestFullscreen && el.requestFullscreen();
    } else {
        document.exitFullscreen && document.exitFullscreen();
    }
};

// 统一的尺寸变化处理
const handleResize = () => {
    isFullscreen.value = !!document.fullscreenElement;
    if (threeManager) {
        threeManager.handleResize();
    }
};

onMounted(() => {
    document.addEventListener('fullscreenchange', handleResize);
    window.addEventListener('resize', handleResize, { passive: true });
});

onBeforeUnmount(() => {
    threeManager && threeManager.dispose();
    document.removeEventListener('fullscreenchange', handleResize);
    window.removeEventListener('resize', handleResize);
});
</script>

<style scoped lang="less">
.button {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #00000080;
    color: #fff;
    cursor: pointer;
    width: 100px;
    height: 100px;
    font-size: 24px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 全屏切换按钮 */
.fs-btn {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 28px;
    height: 28px;
    border-radius: 6px;
    border: 1px solid rgba(255, 255, 255, .25);
    background: rgba(0, 0, 0, .45);
    color: #f8fbff;
    font-size: 14px;
    line-height: 1;
    display: grid;
    place-items: center;
    cursor: pointer;
    z-index: 4;
}

.fs-btn:hover {
    background: rgba(0, 0, 0, .6);
}

/* 进度条样式 */
.my-progress {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 70%;
    max-width: 420px;
    min-width: 200px;
    z-index: 3;
    pointer-events: none;
    height: 12px;
    display: flex;
    align-items: center;
    gap: 8px;

    .my-progress-bar {
        flex: 1 1 auto;
        height: 100%;
        background: rgba(255, 255, 255, 0.25);
        border-radius: 999px;
        overflow: hidden;
    }

    .my-progress-bar__inner {
        height: 100%;
        background: #fff;
        border-radius: 999px;
    }
}

/* 外部百分比文本样式（在进度条右侧） */
.my-progress-bar__text {
    font-size: 12px;
    color: #f8fbff;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.35);
    min-width: 36px;
    text-align: right;
}
</style>
